package com.study.controller;

import com.alibaba.fastjson.JSON;
import com.study.vo.JwtToken;
import com.study.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 使用sentinel 保护 RestTemplate 服务间调用
 */
@Slf4j
@RestController
@RequestMapping("/sentinel-rest-template")
public class SentinelRestTemplateController {

    //这是增强的restTemplate
    private final RestTemplate restTemplate;

    public SentinelRestTemplateController(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
    }


    /**
     * 从授权服务中获取 JwtToken
     * 1、流控降级：是针对触点链路中http://127.0.0.1/ecommerce-authority-center/authority/getToken
     * 2、容错降级：对于服务不可用时候、不能生效
     * @param usernameAndPassword
     * @return
     */
    @PostMapping("/get-token")
    public JwtToken getTokenFromAuthorityService(
            @RequestBody UsernameAndPassword usernameAndPassword){

        String requestUrl =
                "http://127.0.0.1:7000/ecommerce-authority-center/authority/getToken";
        log.info("restTemplate request url and body: [{}],[{}]",
                requestUrl, JSON.toJSONString(usernameAndPassword));

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return restTemplate.postForObject(
                requestUrl,
                new HttpEntity<>(JSON.toJSONString(usernameAndPassword),httpHeaders),
                JwtToken.class);
    }

}
